package com.bkhc.product.repository;

import com.bkhc.product.entity.Goods;
import com.bkhc.product.entity.Product;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.stereotype.Repository;
import org.springframework.util.StringUtils;

import javax.persistence.criteria.*;
import java.util.ArrayList;
import java.util.List;

@Repository
public interface GoodsRepository extends JpaRepository<Goods,String> , JpaSpecificationExecutor<Goods> {

    default Page<Goods> findAll(Goods goods, Pageable pageable){
     return findAll(new Specification<Goods>() {
         @Override
         public Predicate toPredicate(Root<Goods> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
             List<Predicate> predicate = new ArrayList<>();

             if(!StringUtils.isEmpty(goods.getProductCode())){
                 predicate.add(criteriaBuilder.equal(root.get("productCode").as(String.class), goods.getProductCode()));
             }
             if(!StringUtils.isEmpty(goods.getProductName())){
                 predicate.add(criteriaBuilder.like(root.get("productName").as(String.class),"%"+goods.getProductName()+"%"));
             }
             if(!StringUtils.isEmpty(goods.getGoodsCode())){
                 predicate.add(criteriaBuilder.equal(root.get("goodsCode").as(String.class), goods.getGoodsCode()));
             }
             if(goods.getStatus()!=null){
                 predicate.add(criteriaBuilder.equal(root.get("status").as(String.class), goods.getStatus().getCode()));
             }
             Predicate[] pre = new Predicate[predicate.size()];

             return criteriaQuery.where(predicate.toArray(pre)).getRestriction();
         }
     },pageable);
    }

    void deleteByGoodsCode(String goodsCode);

    void deleteByProductCode(String productCode);

    List<Goods> findByProductCode(String productCode);

    Goods findByGoodsCode(String goodsCode);

    List<Goods> findByProductCodeIn(List<String> productCodes);
}
